import 'dart:ffi';
import 'dart:io';

import 'package:path_provider/path_provider.dart';

import 'util.dart';

class FileManager {
  Future<String> loadCache() async {
    var tempDir = await getTemporaryDirectory();
    var value = await _getTotalSizeOfFilesInDir(tempDir);
    Get.log('临时目录大小: ' + value.toString());
    //清除缓存
    return renderSize(value);
  }

  Future<String> tempPath(String name) async {
    var tempDir = await getTemporaryDirectory();
    return tempDir.path + '/' + name;
  }

  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      if (await file.exists() == false) {
        return 0;
      }
      final List children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        total += await _getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }

  Future<int> fileSize(String? path) async {
    if (path == null) {
      return 0;
    }
    var _file = File(path);
    var _value = await _file.length();
    return _value.toInt();
  }

  Future<String> getFileSize(String? path) async {
    if (path == null) {
      return '0';
    }
    var _file = File(path);
    var _value = await _file.length();
    return renderSize(_value.toDouble());
  }

  String renderSize(double? value) {
    if (null == value) {
      return '0';
    }
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value! > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

//递归方式删除目录
  Future delTemp() async {
    var tempDir = await getTemporaryDirectory();
    await delDir(tempDir);
  }

  Future delDir(FileSystemEntity file) async {
    if (file is Directory) {
      if (await file.exists() == false) {
        return;
      }
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    await file.delete();
  }

  Future<void> delPath(String? path) async {
    if (path != null) {
      await File(path).delete();
    }
  }
}
